package com.woniuxy.redis01.service;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

/**
 * @Author author
 * @Create 2023-10-27 14:51
 */
@Service
public class SomeSerevice {

    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    @Autowired
    RedissonClient redissonClient;

    public String test() {
        ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue();
        String str;
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        if(opsForValue.get("a")==null){
            System.out.println("缓存没有，数据库查询,存入缓存");
            str="aaa";
            opsForValue.set("a", str);
        }else{
            System.out.println("缓存有数据，缓存查询");
            str= (String) opsForValue.get("a");
        }
        return str;
    }


//    public void incr() {
//        try {
//            Thread.sleep(5);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }
////        语句，指令     i++;
////        redis 是单线程的
//        redisTemplate.opsForValue().increment("num");
//    }

    //进程内锁：管理一个进程的多个线程
//    public void incr() {
//        ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue();
//        //使用setnx向redis存入数据模拟加锁
//        Boolean flag = opsForValue.setIfAbsent("lock", "xxx", 10, TimeUnit.SECONDS);
//        //flag值false，key存在，加锁失败
//        if(!flag){
//            //自旋锁
//            //加锁失败，等待，
//            try {
//                Thread.sleep(5);
//            } catch (InterruptedException e) {
//                throw new RuntimeException(e);
//            }
//            //继续尝试获取锁
//            incr();
//            return;
//        }
//        int num;
//        if(opsForValue.get("num")==null){
//            num=1;
//        }else{
//           num= Integer.parseInt(opsForValue.get("num").toString());
//           num++;
//        }
//        opsForValue.set("num", num);
//        System.out.println("num="+num);
//        //主业务执行结束,删锁
//        redisTemplate.delete("lock");
//    }
    public void incr() {
        //获取锁对象
        RLock lock = redissonClient.getLock("lock");
        //加锁
        lock.lock();
        ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue();
        int num;
        if(opsForValue.get("num")==null){
            num=1;
        }else{
           num= Integer.parseInt(opsForValue.get("num").toString());
           num++;
        }
        opsForValue.set("num", num);
        System.out.println("num="+num);
        //删锁
        lock.unlock();
    }


}
